<%@page  import="merlin.beans.*,merlin.dao.*,merlin.managers.*,merlin.servlets.*,merlin.utils.*" %>

<%!
	// User types
	static final Integer USER_TYPE_MERLIN_RESEARCHER = new Integer(1);
	static final Integer USER_TYPE_FREE_UPDATES = new Integer(2);

%>


<%
	// sanity check
	if(session.getAttribute("username") == null){
		response.sendRedirect("login.jsp");
		return;
	}


	ApplicationResources resource = ApplicationResources.getInstance();

	String separatorString = resource.getProperty("separatorString");
	String separatorPattern = resource.getProperty("separatorPattern");
%>

<html>
	<head>
		<meta HTTP-EQUIV="Cache-Control"  CONTENT="no-cache" />
		<meta HTTP-EQUIV="Expires"        CONTENT="1 Jan 1980" />
		<meta HTTP-EQUIV="MaxAge"         CONTENT="0" />
		<meta HTTP-EQUIV="Pragma-Control" CONTENT="no-cache" />

		<!-- begin imports for creation of the tabs -->
		<link rel="stylesheet" type="text/css" href="mr_tabs/tabcontent.css" />
		<script type="text/javascript" src="mr_tabs/tabcontent.js">
		</script>
		<!-- ends imports for creation of the tabs -->

		<!-- begin DWR imports -->
		<script type='text/javascript' src='dwr/interface/MsalResearchersManager.js'></script>
		<script type='text/javascript' src='dwr/engine.js'></script>
		<script type='text/javascript' src='dwr/util.js'></script>
		<!-- ends DWR imports -->

		<!-- begin Prototype import -->
		<script type='text/javascript' src='mr_scripts/prototype.js'></script>
		<!-- ends Prototype import -->

		<!-- begin imports for Settings Menu -->
		<link rel="stylesheet" type="text/css" href="mr_menus/themes/office_xp/office_xp.css" />
		<script type="text/javascript" src="mr_menus/jsdomenubar.js"></script>
		<script type="text/javascript" src="mr_menus/jsdomenu.js"></script>
		<script type="text/javascript" src="mr_menus/jsdomenu.inc.freeupdates.js"></script>
		<!-- ends imports for Settings Menu -->


		<script>

			// add a trim() function prototype to the String class.
			String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };

			// Used to determine if a logout comand has been sent or not. It is set to "true"
			// when the user clicks on the "send List" button, or when he clicks the "Logout" link.
			// This variable is used by the logOutOnUnload() function, which gets executed on the unloading of this page.
			// The logOutOnUnload() function invokes an asynchronous call on the server with the
			// mode=logout request parameter. This flag prevents a spurious call , when a mail
			// is being generated, which also results in the unloading of this page but also
			// results in a session invalidation activity on the server end.
			// The logOutOnUnload() function is primarily designed to be executed in case the user simply
			// closes the browser window without properly logging out.
			var logoutCommandSent = false;

			// The company that was added most recently into the "Selected companies" list on tab 1.
			// It is used in the Tab 3 company details diaplay.
			var lastAddedCompanyNumber = null;
			var lastAddedCompanyName = null;

			// Companies that belong to this report.
   			var arrCompanies = null;

			// flag to determine from where the user has reached the tab 3.
   			var updateCompanyFromTab = null;

   			// constants for updateCompanyFromTab variable.
   			var TAB_ADD_COMPANY = 1;
   			var TAB_WEBSITE_DETAILS= 2;

			function newXMLHttpRequest() {

				var xmlreq = false;

				if (window.XMLHttpRequest) {
					// Create XMLHttpRequest object in non-Microsoft browsers
	    			xmlreq = new XMLHttpRequest();
				} else if (window.ActiveXObject) {
					// Create XMLHttpRequest via MS ActiveX
					try {
						// Try to create XMLHttpRequest in later versions
						// of Internet Explorer
						xmlreq = new ActiveXObject("Msxml2.XMLHTTP");
					} catch (e1) {
						// Failed to create required ActiveXObject
						try {
							// Try version supported by older versions
							// of Internet Explorer
							xmlreq = new ActiveXObject("Microsoft.XMLHTTP");
						} catch (e2) {
							// Unable to create an XMLHttpRequest with ActiveX
						}
					}
				}
				return xmlreq;
			}

			// function to force a log-out activity when the window is getting unloaded.
			// this is a backup function in case the user has not logged out cleanly.
			function logOutOnUnload(){
				if(!logoutCommandSent){
					// Obtain an XMLHttpRequest instance
					var req = newXMLHttpRequest();

					// Set the handler function to receive callback notifications
					// from the request object
					//var handlerFunction = getReadyStateHandler(req, updatePage);
					//req.onreadystatechange = handlerFunction;

					// Open an HTTP POST connection to the shopping cart servlet.
					// Third parameter specifies request is asynchronous.
					req.open("POST", "merlin", true);

					// Specify that the body of the request contains form data
					req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

					// Send form encoded data stating that I want to add the
					// specified item to the cart.
					req.send("mode=logout");
				}
			}

			// function which gets called when the usre clicks the "log out" link.
			function logOut(frm){
				logoutCommandSent = true;
				document.frmSearch.mode.value	= "logout";
				document.frmSearch.action		= "merlin";
				document.frmSearch.target		= "_top";
				document.frmSearch.submit();
			}

			////////////// Utility Functions ////////////////////

			function disableEnable(bFlag){
				document.frmSearch.txtSearch.disabled = bFlag;
				document.frmSearch.btnSearch.disabled = bFlag;
				document.frmSearch.lstCompanies.disabled = bFlag;
				document.frmSearch.btnAddCompany.disabled = bFlag;
				document.frmSearch.btnRemoveCompany.disabled = bFlag;
				document.frmSearch.btnUpdate.disabled = bFlag;
				document.frmSearch.lstSelectedCompanies.disabled = bFlag;
				document.frmSearch.lstDirectors.disabled = bFlag;
				document.frmSearch.btnPrintPDF.disabled = bFlag;
			}

			function isBlank(str){
				var len = str.length;
				if(len==0)return true;	// zero-length string
				for(i=0;i<len;i++){
					if(str.charAt(i) !=' ' && str.charAt(i) !='\n')return false; //some character is there
				}
				return true;
			}

			function getSelectedCompanies(frm){

				var lstLen = frm.lstSelectedCompanies.length;
				if(lstLen == 0 )return "";

				var reportTitles ="";
				for(i=0;i < lstLen - 1;i++){
					reportTitles += frm.lstSelectedCompanies.options[i].value + "<%=separatorString %>" + frm.lstSelectedCompanies.options[i].text + "<%=separatorString %>";
				}
				reportTitles += frm.lstSelectedCompanies.options[lstLen-1].value + "<%=separatorString %>" + frm.lstSelectedCompanies.options[lstLen-1].text

				return reportTitles;
			}
			////////////// Ends Utility Functions //////////////////

			/////////////////Message Display Functions ///////////
			function displayMessage(message){
				message = "<SPAN style='color:GREEN; font: 12px arial, verdana, sans-serif ;font-weight:bold;'>" + message + "</SPAN>"
				var divMessage ;
				if(document.all){
					// IE 4+
					divMessage 	= document.all("divMessage");
				}else if(document.getElementById){
					// Mozilla/NS 6+/Firefox
					divMessage 	= document.getElementById("divMessage");
				}else if(document.layers){
					divMessage 	= document.layers["divMessage"];
				}
				divMessage.innerHTML = message;
			}

			function displayError(errMessage){
				errMessage = "<SPAN style='color:red; font: 12px arial, verdana, sans-serif ;font-weight:bold;'>" + errMessage + "</SPAN>"
				var divMessage ;
				if(document.all){
					// IE 4+
					divMessage 	= document.all("divMessage");
				}else if(document.getElementById){
					// Mozilla/NS 6+/Firefox
					divMessage 	= document.getElementById("divMessage");
				}else if(document.layers){
					divMessage 	= document.layers["divMessage"];
				}
				divMessage.innerHTML = errMessage;
			}

			function clearMessage(){
				var emptyMessage = "<SPAN style='font: 12px arial, verdana, sans-serif ;font-weight:bold;'>&nbsp;</SPAN>"
				var divMessage ;
				if(document.all){
					// IE 4+
					divMessage 	= document.all("divMessage");
				}else if(document.getElementById){
					// Mozilla/NS 6+/Firefox
					divMessage 	= document.getElementById("divMessage");
				}else if(document.layers){
					divMessage 	= document.layers["divMessage"];
				}
				divMessage.innerHTML = emptyMessage;
			}

			function displayNumSelectedCompanies(lst){
				var txtSingle   = " Company to include in your new report<br>(click to delete a company)";
				var txtMultiple = " Companies to include in your new report<br>(click to delete a company)";
				var spnMessage ;
				if(document.all){
					// IE 4+
					spnMessage 	= document.all("spnSelectedCompanies");
				}else if(document.getElementById){
					// Mozilla/NS 6+/Firefox
					spnMessage 	= document.getElementById("spnSelectedCompanies");
				}else if(document.layers){
					spnMessage 	= document.layers["spnSelectedCompanies"];
				}
				if(lst.length == 1){
					spnMessage.innerHTML = lst.length + txtSingle ;
				}else{
					spnMessage.innerHTML = lst.length + txtMultiple;
				}
			}

			function cleanAllEntries(){
				var frm = document.frmSearch;

				var divAddress , divShareholders ,divBusinessDescription,divSummaryFinancial;

				if(document.all){
					// IE 4+
					divAddress 				= document.all("divAddress");
					divShareholders 		= document.all("divShareholders");
					divBusinessDescription 	= document.all("divBusinessDescription");
					divSummaryFinancial 	= document.all("divSummaryFinancial");
					divSubsidiary			= document.all("divSubsidiary");
				}else if(document.getElementById){
					// Mozilla/NS 6+/Firefox
					divAddress 				= document.getElementById("divAddress");
					divShareholders 		= document.getElementById("divShareholders");
					divBusinessDescription 	= document.getElementById("divBusinessDescription");
					divSummaryFinancial		= document.getElementById("divSummaryFinancial");
					divSubsidiary			= document.getElementById("divSubsidiary");
				}else if(document.layers){
					divAddress 				= document.layers["divAddress"];
					divShareholders 		= document.layers["divShareholders"];
					divBusinessDescription 	= document.layers["divBusinessDescription"];
					divSummaryFinancial		= document.layers["divSummaryFinancial"];
					divSubsidiary			= document.getElementById("divSubsidiary");
				}
				divAddress.innerHTML 				= "";
				divShareholders.innerHTML   		= "";
				divBusinessDescription.innerHTML 	= "";
	            divSummaryFinancial.innerHTML		= "";
	            divSubsidiary.innerHTML				= "";


				var lstCompanies = frm.lstCompanies;
				// Remove all the previous entries in the lstCompanies select box
				for(i=lstCompanies.length-1;i>=0;i--){
					lstCompanies.remove(i);
				}

				var lstDirectors = frm.lstDirectors;
				// Remove all the previous entries
				for(i=lstDirectors.length-1;i>=0;i--){
					lstDirectors.remove(i);
				}
			}

			//////////////Ends Message Display Functions /////////

			//////////////Search Functions //////////////////////
			function searchCompanyByKeyword(strSearch,frm){

				if(isBlank(strSearch)){
					alert("Cannot leave the search field blank");
					return false;
				}
				if(strSearch.length < 3){
					alert("Enter at least 3 characters in the search field");
					return false;
				}

				if(isSessionValid()){
					// disable the various UI components so that the user cannot generate
					// another request as long as the search is going on.
					disableEnable(true);

					//parent.frameMessage.displayMessage("Searching...");
					displayMessage("Searching.....");
	   				parent.frameSearch.document.frmSearch.mode.value="searchCompanyByKeyword";
	   				parent.frameSearch.document.frmSearch.hidSearch.value=strSearch;
	   				parent.frameSearch.document.frmSearch.hidCompanies.value = getSelectedCompanies(frm);
	   				parent.frameSearch.document.frmSearch.hidSearchType.value = getSearchType(frm);
	   				parent.frameSearch.document.frmSearch.submit();
	   				return true;
				}
			}

			/**
			* 	Determine whether the search for companies (search word entered in the search box),
			*	is alpha-key based or keywrd based.
			*/
			function getSearchType(frm){
				if(frm.radSearchType[0].checked){
					return frm.radSearchType[0].value;
				}else{
					return frm.radSearchType[1].value;
				}
			}

			function searchCompanyByCompanyNumber(strNumber,frm){
				if(strNumber == null || strNumber == "" || strNumber == "-1"){
					return;
				}

				if(isSessionValid()){
					// disable the various UI components so that the user cannot generate
					// another request as long as the search is going on.
					disableEnable(true);

					//parent.frameMessage.displayMessage("Searching...");
					displayMessage("Searching.....");
	   				parent.frameSearch.document.frmSearch.mode.value="searchCompanyByCompanyNumber";
	   				parent.frameSearch.document.frmSearch.hidSearch.value=strNumber;
	   				parent.frameSearch.document.frmSearch.hidCompanies.value = getSelectedCompanies(frm);
	   				parent.frameSearch.document.frmSearch.submit();
				}
			}

			function searchCompanyByDirector(strNumber,frm){
				if(strNumber == null || strNumber == "" || strNumber == "-1"){
					return;
				}

				if(isSessionValid()){
					// disable the various UI components so that the user cannot generate
					// another request as long as the search is going on.
					disableEnable(true);

					//parent.frameMessage.displayMessage("Searching...");
					displayMessage("Searching.....");
					parent.frameSearch.document.frmSearch.mode.value="searchCompanyByDirector";
	   				parent.frameSearch.document.frmSearch.hidSearch.value=strNumber;
	   				parent.frameSearch.document.frmSearch.hidCompanies.value = getSelectedCompanies(frm);
	   				parent.frameSearch.document.frmSearch.submit();
				}
			}
			//////////////Ends Search Functions /////////////////////////

			function transferCompany(lstFrom,lstTo){
				try{
					var index = lstFrom.selectedIndex;
					if(index == -1){
						alert("Select a company to add");
						return;
					}
					// check if the company already exists in the selected companies list.
					var valCompany = lstFrom.options[index].value;
					var exists = false;
					var lstTolen = lstTo.length;
					for(j=0;j<lstTolen;j++){
						if(valCompany == lstTo.options[j].value){
							alert("Company already selected");
        					exists = true;
	        				lstFrom.options[index].selected = false;
							break;
	    		    	}
    	    		}
			        if(! exists){
						// add the company to the list
	    			    var aOption = document.createElement("OPTION");
						aOption.text = lstFrom.options[index].text;
						aOption.value = lstFrom.options[index].value;
						// browser specific addition, different in Mac Safari.
						if(navigator.userAgent.indexOf("Safari") > -1){
							// Mac Safari
							lstTo.add(aOption);
						}else{
							// other browsers.
							lstTo.options.add(aOption);
						}

						// and remove it from the other
						lstFrom.remove(index);

						// sort the data.
						sortSelect(lstTo);

						displayNumSelectedCompanies(lstTo);
						sendCompanyListForStorage();

						// fetch details for Tab 3 activity.
						lastAddedCompanyNumber = aOption.value;
						lastAddedCompanyName = aOption.text;
						fetchCompanyWebsiteDetails(aOption.value);
					}
				}catch(e){
					alert("transferCompany : " + e.message);
				}
			}

			function sendReportData(frm){
				if(frm.lstSelectedCompanies.length == 0){
					alert("There must be at least one company selected");
					return;
				}

				if(isSessionValid()){
					//parent.frameMessage.displayMessage("Sending Mail...");
					displayMessage("Sending Mail...");

	    			logoutCommandSent = true;
	    			frm.mode.value="sendMail";
	    			frm.hidCompanies.value= getSelectedCompanies(frm);
	    			frm.submit();
				}
			}

			function deleteCompany(lst){
				var isAnySelected = false;
				for(i = lst.length -1;i>=0;i--){
					if(lst.options[i].selected == true){
						lst.options[i] = null;
						isAnySelected = true;
					}
				}
				if(!isAnySelected){
					alert("Select a company to delete");
				}else{
					if(isSessionValid()){
						displayNumSelectedCompanies(lst);
						sendCompanyListForStorage();
					}
				}
			}

        	// sort function - ascending (case-insensitive)
	        function sortFuncAsc(record1, record2) {
    	        var value1 = record1.optText.toLowerCase();
        	    var value2 = record2.optText.toLowerCase();
            	if (value1 > value2) return(1);
	            if (value1 < value2) return(-1);
    	        return(0);
        	}

		    // sort the select object in ascending order.
			function sortSelect(selectToSort) {
				try{
					// copy options into an array
				    var myOptions = new Array();
					for (var loop=0; loop<selectToSort.options.length; loop++) {
						myOptions[loop] = { optText:selectToSort.options[loop].text, optValue:selectToSort.options[loop].value };
					}

					// sort array
					myOptions.sort(sortFuncAsc);

					// copy sorted options from array back to select box
					selectToSort.options.length = 0;

					// browser identification
					var isSafari =	(navigator.userAgent.indexOf("Safari") > -1)? true: false;

					for (var loop=0; loop<myOptions.length; loop++) {
						var optObj = document.createElement('option');
						optObj.text = myOptions[loop].optText;
						optObj.value = myOptions[loop].optValue;
						if(isSafari){
							selectToSort.add(optObj);
						}else{
							selectToSort.options.add(optObj);
						}
					}
				}catch(e){
					alert("sortSelect : " + e.message);
				}
			}

			function generatePDF(companyId){
				if(companyId == null || companyId==""){
					alert("Please select a company from the search results list");
				}else{
					if(isSessionValid()){
						// open on a new window
						window.open("merlin?mode=createPDF&companyId=" + companyId,"pdf","height=600,width=600,resizable=yes,menubar=yes,scrollbars=yes,toolbar=no");
   		   			}
		   		}
			}

			/****
				Begins scripts for Tab 2 (Source List Window)
			****/

			// Determines whether the user is opening up the tab for the first time since logging in.
			// This is used to load the initial source list.
			var bFirstTimeOnSourceListWindow = true;

			var reportId	= <%= session.getAttribute("reportId") %>;
			var	username	= "<%=session.getAttribute("username")%>";
	   		var	reportTitle	= "<%=session.getAttribute("reportTitle")%>";

			var arrSourceLists = new Array();

			var newSourceListEntry = true;	// whether the user is entering a new URL or updating an existing one.

			var currentEntryIndex = -1;	// the entry in the listbox which is being viewed/modified.

			/**
			*	Function that gets called the first time a researcher opens the tab 2.
			*/
			function tabSourceListWindowOpened(){
				if(bFirstTimeOnSourceListWindow){
					bFirstTimeOnSourceListWindow = false;
                    MsalResearchersManager.getIndustrySourceListings(reportId,handleGetIndustrySourceListings);
                    createNewURL(document.frmSourceDetails);
				}
			}

			/**
			* 	DWR callback handler
			*/
			function handleGetIndustrySourceListings(data){

				arrSourceLists = data;
				var sel = document.frmSourceList.selSourceList;

				// first remove all the elements from the select box.
				for(var i = sel.length - 1; i>=0;i--){
					sel.options[i] = null;
				}

				// now add the new options.
				for(var i=0;i < arrSourceLists.length;i++){
					sel.options[i] = new Option(arrSourceLists[i].url, arrSourceLists[i].sourceId);
				}

				currentEntryIndex = -1;
				newSourceListEntry = true;

			}

			/**
			* Function to display the detailed information on the right-side panel.
			*/
			function displaySourceDetails(frm,index){
				if(index > -1 && index < arrSourceLists.length){
					currentEntryIndex = index;
					newSourceListEntry = false;
					var objSource = arrSourceLists[index];
					frm.txtURL.value					= objSource.url;
					frm.txtNotes.value					= objSource.notes;
					frm.chkAssociationIndicator.checked	= objSource.associationIndicator;
					frm.radQualityScore[parseInt(objSource.qualityScore)].checked = true;
					frm.txtDateLastChecked.value		= objSource.dateLastCheckedString;
					frm.txtURL.focus();
					displaySourceListMessage("Edit <b>" + truncateToFit(objSource.url) + "</b>");
				}
			}

			/**
			* 	Clears all previous text in the panel 2 components.
			*/
			function createNewURL(frm){
				currentEntryIndex = -1;
				newSourceListEntry = true;
                clearAllEntries(frm);
				frm.txtURL.focus();
				displaySourceListMessage("Add New Source List");
			}


            /**
            *	Save/update the current source list data.
            */
			function updateSourceList(frm){
				if(isBlank(frm.txtURL.value)){
					alert("URL field is empty");
					frm.txtURL.focus();
					return;
				}
				if(isSessionValid()){
					if(newSourceListEntry){
						// it is a new entry.
						MsalResearchersManager.addIndustryListing(reportId,frm.txtURL.value,frm.txtNotes.value,frm.chkAssociationIndicator.checked,getQualityScore(frm),frm.txtDateLastChecked.value,handleUpdateSourceList);
					}else{
						if(currentEntryIndex != -1){
							// it is an update
							MsalResearchersManager.updateIndustryListing(arrSourceLists[currentEntryIndex].sourceId,reportId,frm.txtURL.value,frm.txtNotes.value,frm.chkAssociationIndicator.checked,getQualityScore(frm),frm.txtDateLastChecked.value,handleUpdateSourceList);
						}
					}
				}
			}

			/**
			*	DWR callback handler.
			*/
			function handleUpdateSourceList(data){
				if(parseInt(data) > 0){
					if(newSourceListEntry){
						displaySourceListMessage("record added");
					}else{
						displaySourceListMessage("record updated");
					}
					// reflect the updated records in the list.
                    clearAllEntries(document.frmSourceDetails);
                    MsalResearchersManager.getIndustrySourceListings(reportId,handleGetIndustrySourceListings);
				}
			}

			/**
			* 	Send all the source lists to the server for generating email.
			*/
			function emailSourceList(){
				if(arrSourceLists != null && arrSourceLists.length > 0){
					DWRUtil.useLoadingMessage();
					MsalResearchersManager.emailSourceList(username,reportTitle,arrSourceLists,handleEmailSourceList);
				}else{
					alert("there are no records to send");
				}
			}

			/**
			* 	DWR callback handler.
			*/
			function handleEmailSourceList(message){
				  displaySourceListMessage(message);
			}

			function deleteSourceList(frm){
				if(! newSourceListEntry){
					MsalResearchersManager.deleteIndustrySourceListing(arrSourceLists[currentEntryIndex].sourceId,handleDeleteSourceList);
				}
			}

			function handleDeleteSourceList(data){
				if(parseInt(data) > 0){
					displaySourceListMessage("record deleted");
				}else{
					displaySourceListMessage("record could not be deleted");
				}
				// reflect the updated records in the list.
				clearAllEntries(document.frmSourceDetails);
				MsalResearchersManager.getIndustrySourceListings(reportId,handleGetIndustrySourceListings);
			}

			function clearAllEntries(frm){
				document.frmSourceList.selSourceList.selectedIndex = -1;
				frm.txtURL.value					= "";
				frm.txtNotes.value					= "";
				frm.chkAssociationIndicator.checked	= false;
				frm.radQualityScore[0].checked 		= true;
				frm.txtDateLastChecked.value		= parseDate();
			}

			function getQualityScore(frm){
				for(var i=0;i<frm.radQualityScore.length;i++){
					if(frm.radQualityScore[i].checked) return i;
				}
			}

			function displaySourceListMessage(messageToDisplay){
				message = "<SPAN style='color:GREEN; font: 11px arial, verdana, sans-serif ;font-weight:normal;'>" + messageToDisplay + "</SPAN>"
				var divMessage ;
				if(document.all){
					// IE 4+
					divMessage 	= document.all("divSourceListMessage");
				}else if(document.getElementById){
					// Mozilla/NS 6+/Firefox
					divMessage 	= document.getElementById("divSourceListMessage");
				}else if(document.layers){
					divMessage 	= document.layers["divSourceListMessage"];
				}
				divMessage.innerHTML = message;
			}

			/**
			* Utility function to create a formatted date string (dd-Mon-yyyy) of the current date.
			*/
			function parseDate(){
				var arrMonths = new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
				var dt = new Date();
				var strDate = (dt.getDate()<10?"0":"") + dt.getDate() + "-" + arrMonths[dt.getMonth()] + "-" + dt.getFullYear();
				return strDate;
			}

			/**
			* 	Function cuts a string if it is more than 40 characters long.
			*/
			function truncateToFit(str){
				if(str.length > 40){
					return str.substring(0,40);
				}else{
					return str;
				}
			}

			function jumpToURL(link){
				link = link.trim();
				if(link.length > 0){
					// if the link doesn't start with http:// or https:// add it to make it a proper URL.
					if(link.toLowerCase().indexOf("http://") != 0 && link.toLowerCase().indexOf("https://") != 0){
						link = "http://" + link;
					}
					window.open(link,"_blank");
				}
				return false;
			}

			function jumpToGoogleSearch(searchCriteria){
				if(document.frmCompanyList.selCompanyList.selectedIndex == -1) return;
				var companyName = arrCompanies[document.frmCompanyList.selCompanyList.selectedIndex][searchCriteria];
				window.open("http://www.google.co.uk/search?q=" + escape(companyName),"_blank");
			}


			// functions related to Tab 3 (website details).
			function fetchCompanyWebsiteDetails(registrationNumber){
				if(isSessionValid()){
					MsalResearchersManager.getCompanyWebsiteDetails(registrationNumber,handleFetchCompanyWebsiteDetails);
				}
			}

			function handleFetchCompanyWebsiteDetails(data){
				var needToBeUpdated = false;
    			var website = "";
    			var email = "";
    			var personalEmail = "", prefix = "", firstName = "", initials = "", surname = "", position = "";
				if(data == null){
					needToBeUpdated = true;
				}else{
				    if(data.website == null || data.email == null || data.personalEmail == null){
				    	needToBeUpdated = true;
				    	website =  (data.website == null ? "" : data.website);
				    	email =  (data.email == null ? "" : data.email);
                        personalEmail = (data.personalEmail == null ? "" : data.personalEmail);
                        prefix = (data.prefix == null ? "" : data.prefix);
						firstName = (data.firstName == null ? "" : data.firstName);
						initials = (data.initials == null ? "" : data.initials);
						surname = (data.surname == null ? "" : data.surname);
						position = (data.position == null ? "" : data.position);
				    }
				}
				if(needToBeUpdated){
					document.frmCompanyDetails.hidRegistrationNumber.value = lastAddedCompanyNumber;
					document.frmCompanyDetails.txtCompanyWebsite.value = website;
					document.frmCompanyDetails.txtCompanyEmail.value = email;
					document.frmCompanyDetails.txtPersonalEmail.value = personalEmail;
					document.frmCompanyDetails.txtPrefix.value = prefix;
					document.frmCompanyDetails.txtFirstName.value = firstName;
					document.frmCompanyDetails.txtInitials.value = initials;
					document.frmCompanyDetails.txtSurname.value = surname;
					document.frmCompanyDetails.txtPosition.value = position;

					$("divCompanyDetails").innerHTML = lastAddedCompanyName + "<br>" + $("divAddress").innerHTML;
					expandtab('maintab', 2);
					$("btnCancel").style.visibility="visible";
					updateCompanyFromTab = TAB_ADD_COMPANY;
				}else{
					clearCompanyDetails();
				}
			}

			function clearCompanyDetails(){
				document.frmCompanyDetails.hidRegistrationNumber.value = "";
				document.frmCompanyDetails.txtCompanyWebsite.value = "";
				document.frmCompanyDetails.txtCompanyEmail.value = "";
				document.frmCompanyDetails.txtPersonalEmail.value = "";
				document.frmCompanyDetails.txtPrefix.value = "";
				document.frmCompanyDetails.txtFirstName.value = "";
				document.frmCompanyDetails.txtInitials.value = "";
				document.frmCompanyDetails.txtSurname.value = "";
				document.frmCompanyDetails.txtPosition.value = "";

				$("divCompanyDetails").innerHTML = "";
			}

			function toggleTab3Controls(bFlag){
				document.frmCompanyDetails.txtCompanyWebsite.disabled = bFlag;
				document.frmCompanyDetails.txtCompanyEmail.disabled = bFlag;
				document.frmCompanyDetails.txtPersonalEmail.disabled = bFlag;
				document.frmCompanyDetails.txtPrefix.disabled = bFlag;
				document.frmCompanyDetails.txtFirstName.disabled = bFlag;
				document.frmCompanyDetails.txtInitials.disabled = bFlag;
				document.frmCompanyDetails.txtSurname.disabled = bFlag;
				document.frmCompanyDetails.txtPosition.disabled = bFlag;
				document.frmCompanyList.selCompanyList.disabled = bFlag;
				document.frmCompanyDetails.btnCancel.disabled = bFlag;
				document.frmCompanyDetails.btnUpdate.disabled = bFlag;
				document.frmCompanyDetails.btnSearchName.disabled = bFlag;
				document.frmCompanyDetails.btnSearchPostcode.disabled = bFlag;
				document.frmCompanyDetails.btnGoTo.disabled = bFlag;
			}

			function saveCompanyWebsiteDetails(frm){

				var regNumber		= frm.hidRegistrationNumber.value;
				var companyWebsite	= frm.txtCompanyWebsite.value;
				var companyEmail	= frm.txtCompanyEmail.value;
				var unsubscribe		= frm.chkMailDB.checked;
				var personalEmail	= frm.txtPersonalEmail.value;
				var prefix			= frm.txtPrefix.value;
				var firstName		= frm.txtFirstName.value;
				var initials 		= frm.txtInitials.value;
				var surname			= frm.txtSurname.value;
				var position		= frm.txtPosition.value;
				var personalUnsubscribe = frm.chkPersonalMailDB.checked;

				// change the blank values to null.
				companyWebsite	= isBlank(companyWebsite) ? null : companyWebsite;
				companyEmail	= isBlank(companyEmail) ? null : companyEmail;
				personalEmail	= isBlank(personalEmail) ? null : personalEmail;

				if(regNumber == null || regNumber == "")return;

				// validate website address.
				if(companyWebsite != null){
					companyWebsite = companyWebsite.trim();
					// delete any trailing '.'
					if(companyWebsite.trim().match(".$")=="."){
						companyWebsite = companyWebsite.trim().substring(0,companyWebsite.trim().length - 1);
					}

					frm.txtCompanyWebsite.value = companyWebsite;

					if (!isValidWebsiteURL(companyWebsite)){
						alert("invalid website URL");
						return;
					}
				}

				// strip trailing '.' in email address if present.
				if(companyEmail != null){
					companyEmail = companyEmail.trim();
					if(companyEmail.trim().match(".$")=="."){
						companyEmail = companyEmail.trim().substring(0,companyEmail.trim().length - 1);
					}

					frm.txtCompanyEmail.value =  companyEmail;
				}

				// validate email format if it is not null
				if(companyEmail != null){
					if(!isValidEMailFormat(companyEmail)){
						alert("Generic Email is in invalid format");
						return;
					}
				}

				// strip trailing '.' in email address if present.
				if(personalEmail != null){
					personalEmail = personalEmail.trim();
					if(personalEmail.trim().match(".$")=="."){
						personalEmail = personalEmail.trim().substring(0,personalEmail.trim().length - 1);
					}

					frm.txtPersonalEmail.value =  personalEmail;
				}

				// validate email format if it is not null
				if(personalEmail != null){
					if(!isValidEMailFormat(personalEmail)){
						alert("Personal Email is in invalid format");
						return;
					}
				}

				// If there is an entry for the personal mail id,
				// the fields firstname or initials, and surname must be filled in.
				if(personalEmail != null){
					if((firstName == "" && initials == "") || surname == ""){
						alert("The fields firstname,initials, and surname must also be filled");
						return;
					}
				}

				if(isSessionValid()){
					toggleTab3Controls(true);
					// add the new details into the database.
    	            MsalResearchersManager.saveCompanyWebsiteDetails(regNumber,companyWebsite,companyEmail,unsubscribe,personalEmail,prefix,firstName,initials,surname,position,handleUpdateCompanyWebsiteDetails);
    	        }
			}

			// function to check whether the website format is correct or not.
			function isValidWebsiteURL(websiteUrl){

				websiteUrl = websiteUrl.toLowerCase();

				// should not contain 'http://' or 'https://'
				if(websiteUrl.indexOf("http://") != -1 || websiteUrl.indexOf("https://") != -1 ){
					return false;
				}

				// should not contain any spaces or tabs.
				if(websiteUrl.indexOf(" ") != -1 || websiteUrl.indexOf("\t") != -1){
					return false;
				}

				// starts with 'www.'
				if(websiteUrl.indexOf("www.") != 0){
					return false;
				}

				return true;
			}

			function handleUpdateCompanyWebsiteDetails(data){
				toggleTab3Controls(false);

				switch(updateCompanyFromTab){
					case TAB_ADD_COMPANY :
						expandtab('maintab', 0);
						break;
					case TAB_WEBSITE_DETAILS :
						// update the corrsponding object in arrCompanies.
						var index = document.frmCompanyList.selCompanyList.selectedIndex;
						if(index != -1){
							arrCompanies[index].website = (isBlank(document.frmCompanyDetails.txtCompanyWebsite.value) ? null : document.frmCompanyDetails.txtCompanyWebsite.value);
							arrCompanies[index].email =(isBlank(document.frmCompanyDetails.txtCompanyEmail.value) ? null : document.frmCompanyDetails.txtCompanyEmail.value);
							arrCompanies[index].unsubscribe	= document.frmCompanyDetails.chkMailDB.checked;
							arrCompanies[index].personalEmail = document.frmCompanyDetails.txtPersonalEmail.value;
							arrCompanies[index].prefix = document.frmCompanyDetails.txtPrefix.value;
							arrCompanies[index].firstName = document.frmCompanyDetails.txtFirstName.value;
							arrCompanies[index].initials = document.frmCompanyDetails.txtInitials.value;
							arrCompanies[index].surname = document.frmCompanyDetails.txtSurname.value;
							arrCompanies[index].personalUnsubscribe = document.frmCompanyDetails.chkPersonalMailDB.checked;
							arrCompanies[index].position = document.frmCompanyDetails.txtPosition.value;


							var color = null;
							if((arrCompanies[index].website != null && arrCompanies[index].website.length > 0) && ((arrCompanies[index].email != null && arrCompanies[index].email.length > 0)) || (arrCompanies[index].personalEmail != null && arrCompanies[index].personalEmail.length > 0)){
								color ="green";
							}else{
								color ="black";
							}
							document.frmCompanyList.selCompanyList.options[index].style.color = color;
						}
						break;
				}
			}

			function tabWebsiteDetailsClicked(){
				// Load the companies that are part of this report.
				document.frmCompanyList.selCompanyList.selectedIndex = -1;
				$("btnCancel").style.visibility="hidden";
			}

			function getCompanyWebsiteDetailsByReportId(){
				// Load the companies that are part of this report.
				clearCompanyDetails();
				var list = document.frmCompanyList.selCompanyList;
    			// clear all existing entries.
    			for(var i=list.options.length-1;i>=0;i--){
    				list.remove(i);
    			}
    			if(isSessionValid()){
					DWRUtil.useLoadingMessage();
					MsalResearchersManager.getCompanyWebsiteDetailsByReportId(reportId,handleGetCompanyWebsiteDetailsByReportId);
				}
			}

			function handleGetCompanyWebsiteDetailsByReportId(data){
				arrCompanies = data;
				// render each of them in the list box, olor-coded so that those entries
				// which exist in the websites table are colored green.


				var list = document.frmCompanyList.selCompanyList;

    			//now add the new entries.
    			for(var i=0;i<arrCompanies.length;i++){
    			    var aOption = document.createElement("OPTION");
					aOption.text = arrCompanies[i].companyName;
					aOption.value = arrCompanies[i].registeredNumber;

					if((arrCompanies[i].website != null && arrCompanies[i].website.length > 0) && (arrCompanies[i].email != null && arrCompanies[i].email.length > 0) || (arrCompanies[i].personalEmail != null && arrCompanies[i].personalEmail.length > 0)){
						aOption.style.color="green";
					}

					// browser specific addition, different in Mac Safari.
					if(navigator.userAgent.indexOf("Safari") > -1){
						// Mac Safari
						list.add(aOption);
					}else{
						// other browsers.
						list.options.add(aOption);
					}
    			}
			}

			function displayCompanyDetails(frm,selectedIndex){
				var data = arrCompanies[selectedIndex];
				var needToBeUpdated = false;
    			var website = "";
    			var email = "";

		    	website =  (data.website == null ? "" : data.website);
		    	email =  (data.email == null ? "" : data.email);

				frm.hidRegistrationNumber.value = data.registeredNumber;
				frm.txtCompanyWebsite.value = website;
				frm.txtCompanyEmail.value = email;
				frm.chkMailDB.checked = data.unsubscribe;

				frm.txtPersonalEmail.value = data.personalEmail;
				frm.txtPrefix.value = data.prefix;
				frm.txtFirstName.value = data.firstName;
				frm.txtInitials.value = data.initials;
				frm.txtSurname.value = data.surname;
				frm.txtPosition.value = data.position;

				if(data.addressDetailsUpdated){
					$("divCompanyDetails").innerHTML = data.companyName + emptyIfNull(data.addressLine1) + emptyIfNull(data.addressLine2) + emptyIfNull(data.town) + emptyIfNull(data.county) + emptyIfNull(data.postcode);
				}else{
					if(isSessionValid()){
						// retrieve the company address details from the server.
						MsalResearchersManager.selectLookupDetailsByPK(data.registeredNumber,handleGetCompanyAddressDetails);
					}
				}
				updateCompanyFromTab = TAB_WEBSITE_DETAILS;
			}

			function handleGetCompanyAddressDetails(data){
				//first search for the correct object in the array
				for(var i=0;i<arrCompanies.length;i++){
					var obj = arrCompanies[i];
					if(obj.registeredNumber == data.companyNumber){
						//copy all the relevant details from the data object into the corresponding array object.
						obj.addressLine1	= data.addressLine1;
						obj.addressLine2	= data.addressLine2;
						obj.town			= data.town;
						obj.county			= data.county;
						obj.postcode		= data.postcode;

						obj.addressDetailsUpdated = true;

						// update the screen UI.
						$("divCompanyDetails").innerHTML = obj.companyName + emptyIfNull(obj.addressLine1) + emptyIfNull(obj.addressLine2) + emptyIfNull(obj.town) + emptyIfNull(obj.county) + emptyIfNull(obj.postcode);
						break;
					}
				}
			}

			function emptyIfNull(data){
				if(data != null && data.length > 0){
					return "<br>" + data;
				}else{
					return "";
				}
			}

			//validate the format of the e-mail address
			function isValidEMailFormat(str){
				var at="@"
				var dot="."
				var lat=str.indexOf(at)
				var lstr=str.length
				var ldot=str.indexOf(dot)
				if (str.indexOf(at)==-1){
					return false
				}

				if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
					return false
				}

				if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
					return false
				}

				if (str.indexOf(at,(lat+1))!=-1){
					return false
				}

				if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
					return false
				}

				if (str.indexOf(dot,(lat+2))==-1){
					return false
				}

				if (str.indexOf(" ")!=-1){
					return false
				}

				// no tabs
				if(str.indexOf("\t") != -1){
					return false;
				}

				// doesn't end with dot.
				if(str.substring(lstr-1) == "."){
					return false;
				}

				return true;
			}

	    	function sendCompanyListForStorage(){
	    		if(isSessionValid()){
		    		var companies = getSelectedCompanies(document.frmSearch);
		    		MsalResearchersManager.storeSelectedCompanies(username,companies,reportId,null);
		    	}
	    	}

			/**
			* Function to capitalize words.
			*/
			function capitalizeWords(inputString){
				var tmpStr, tmpChar, preString, postString, strlen;
				tmpStr = inputString.toLowerCase();
				stringLen = tmpStr.length;
				if (stringLen > 0){
					for (i = 0; i < stringLen; i++){
						if (i == 0){
							tmpChar = tmpStr.substring(0,1).toUpperCase();
							postString = tmpStr.substring(1,stringLen);
							tmpStr = tmpChar + postString;
						}else{
							tmpChar = tmpStr.substring(i,i+1);
							if (tmpChar == " " && i < (stringLen-1)){
								tmpChar = tmpStr.substring(i+1,i+2).toUpperCase();
								preString = tmpStr.substring(0,i+1);
								postString = tmpStr.substring(i+2,stringLen);
								tmpStr = preString + tmpChar + postString;
							}
						}
					}
				}
				return tmpStr;
			}

			function fillPosition(txt){
				var str = txt.value.toLowerCase();
				switch(str){
					case 'd'  :
						txt.value = "Director";
						break;
					case 'md' :
						txt.value = "Managing Director";
						break;
					case 'fd' :
						txt.value = "Financial Director";
						break;
					case 'sd' :
						txt.value = "Sales Director";
						break;
					case 'ceo':
						txt.value = "Chief Executive Officer";
						break;
					case 'ce' :
						txt.value = "Chief Executive";
						break;
					case 'c'  :
						txt.value = "Chairman";
						break;
				}
			}

			function fillInitials(frm){
				if(frm.txtInitials.value == ""){
					if(frm.txtFirstName.value.length >0){
						frm.txtInitials.value = frm.txtFirstName.value.substring(0,1).toUpperCase();
					}
				}
			}
		</script>

		<script>
			// the session invalidation duration, in milliseconds
			var lastAccessedTime = new Date().getTime();

			// the session invalidation duration, in milliseconds
			var sessionDuration = <%= session.getMaxInactiveInterval()%> * 1000;

			var timerPointer = -1;
			var timerWarning = -1;

			/**
			* 	Function to check if the user is still having a valid session or has timed out.
			*	Adds two timeout functions to the windowd object -
			*		1. a function that shows a warning message to the user that his session is about to expire
			*			with an option to stay connected
			*		2. a automatic logout if the session times out.
			*/
			function isSessionValid(){
				var currentTime  = new Date().getTime();

				if((currentTime - lastAccessedTime) < sessionDuration){
					// session is valid.
					lastAccessedTime = currentTime;

					// cancel the existing timer(if any),and start again.
					if(timerPointer != - 1)clearTimeout(timerPointer);
					if(timerWarning != - 1)clearTimeout(timerWarning);

					timerPointer = setTimeout('logOut(document.frm)',sessionDuration);
					timerWarning = setTimeout('showLogoutWarning()',sessionDuration - 10000);

					return true;
				}else{
					// session has timed out, send to logout procedure.
					logOut(document.frm);
					return false;
				}
			}

			/**
			*  Shows the logout warning DIV.
			*/
			function showLogoutWarning(){
				document.getElementById("divStayLoggedIn").style.visibility = "visible";
			}

			/**
			* 	A function that provides the user the option to stay logged on 10 secs before the logout event.
			*/
			function stayLoggedOn(){
				if(isSessionValid()){
					document.getElementById("divStayLoggedIn").style.visibility = "hidden";
					MsalResearchersManager.stayConnected();
				}
			}
		</script>

	    <link href="css/master.css" rel="stylesheet" type="text/css">
	</head>
	<body onload ="isSessionValid();" onunload="logOutOnUnload()">

    <jsp:include page = "mr_headerFreeUpdates.jsp"/>

		<!-- DIV for displaying the option of staying logged in 10 seconds before the actual logoff -->
		<div align="center" id="divStayLoggedIn" style="color:black;background-color:#7823CD;visibility:hidden;position:absolute;left:280px;top:350px">
			<%= request.getHeader("user-agent").indexOf("MSIE") != -1 ? "<BR>" : "" %>
			<h3 style="padding: 2px;font-family: Verdana, Helvetica, Arial, sans-serif;font-size: 15px;vertical-align:center;cursor:hand;" onclick="stayLoggedOn()">&nbsp; Click here to stay logged in to the Researcher Service &nbsp;</h3>
		</div>

		<div align="center">
<table width="750" align="center" cellpadding="0" cellspacing="0" border="0">
 <tr>
  <td>

		<ul id="maintab" class="shadetabs">
			<li class="selected"><a href="#" rel="divCompaniesTab">Company Details&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</a></li>
			<li onclick="tabSourceListWindowOpened()"><a href="#" rel="divSourceListTab">&nbsp;&nbsp;&nbsp;Source Lists&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</a></li>
			<li onclick="tabWebsiteDetailsClicked()"><a href="#" rel="divWebsiteDetailsTab">&nbsp;&nbsp;&nbsp;Website Details&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</a></li>
		</ul>

		<!-- tab 1 starts -->
		<div id="divCompaniesTab" style="MARGIN:0; BACKGROUND-COLOR: white;border-style:solid;border-width:1px;border-color:yellow">
			<br>
		    <DIV ALIGN="CENTER" ID="divMessage">&nbsp;</DIV>
		    <br>

			<FORM name="frmSearch" method="post" target="_top" action="merlin" onsubmit="searchCompanyByKeyword(this.txtSearch.value,this);return false;">
				 <input type="hidden" name="hidCompanies">
				 <input type="hidden" name="mode">
						<div style="PADDING-RIGHT: 0px; PADDING-LEFT: 0px; PADDING-BOTTOM: 0px; PADDING-TOP: 0px">
							<table style="MARGIN: 0px 0px 0px 9px; WIDTH: 720px" cellpadding="1" cellspacing="0">
								<tr>
									<td style="FONT: 11px arial, verdana, sans-serif; WIDTH: 33%">
										<b>Search for <input type="radio" name="radSearchType" value="alphakey" checked>Alphakey or <input type="radio" name="radSearchType" value="keyword"> Keyword (Name, Keyword, Director, Registration Number or Address).</b>
									</td>
								</tr>
								<tr>
									<td>
										<input name="txtSearch" style="TEXT-TRANSFORM: uppercase; WIDTH: 350px;FONT: 11px arial, verdana, sans-serif;"  >
										<input name="btnSearch" type="submit" style="FONT-SIZE: 11px; WIDTH: 95px" value="Search For Firm  >" > <!-- onclick="searchCompanyByKeyword(this.form.txtSearch.value,this.form)" -->
										&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="button"  name="btnPrintPDF" style="FONT-SIZE: 11px; WIDTH: 95px" value="Print PDF" onclick="generatePDF(this.form.lstCompanies.value)">
									</td>
								</tr>
							</table>
						</div>
						<div style="PADDING-RIGHT: 0px; PADDING-LEFT: 0px; PADDING-BOTTOM: 7px; PADDING-TOP: 5px">
							<table style="MARGIN: 0px 0px 0px 9px; WIDTH: 710px" cellpadding="1" cellspacing="0">
								<tr>
									<td style="WIDTH: 260px">
										<span style="FONT: 11px arial, verdana, sans-serif">The following companies were found by this search<br >(click to view a company of interest)</span>
										<SELECT name="lstCompanies" size="4" MULTIPLE style="WIDTH: 250px; FONT: 11px arial, verdana, sans-serif;" onchange="searchCompanyByCompanyNumber(this.value,this.form)">
										</SELECT>
									</td>
									<td style="TEXT-ALIGN: center">
										<input type="button" name="btnAddCompany" value="Add Company  >"  style ="FONT-SIZE: 11px; WIDTH: 130px" onclick="transferCompany(this.form.lstCompanies,this.form.lstSelectedCompanies)">
										<input type="button" name="btnRemoveCompany" value="   < Remove Company" style="FONT-SIZE: 11px; WIDTH: 130px" onclick="deleteCompany(this.form.lstSelectedCompanies)">
										<input type="button" name="btnUpdate" value="Send List" style="FONT-SIZE: 11px; WIDTH: 130px" onclick="sendReportData(this.form)">
									</td>
									<td style="WIDTH: 260px; TEXT-ALIGN: right">
										<span id="spnSelectedCompanies" style="FONT: 11px arial, verdana, sans-serif">Companies to include in your new report<br>(click to delete a company)</span>
										<SELECT name="lstSelectedCompanies" size="4" MULTIPLE style="WIDTH: 250px; FONT: 11px arial, verdana, sans-serif;"> <!-- onchange="searchCompanyByCompanyNumber(this.value,this.form)" -->
										<%
											String strCompanies = (String)session.getAttribute("selectedCompanies");
											if(strCompanies != null && strCompanies.length() > 0){
												String arrCompanies[] = strCompanies.split(separatorPattern);
                                           		for(int i=0;i< arrCompanies.length-1;i+=2){
											  		out.println("<option value=\'" + arrCompanies[i] + "\'>" + arrCompanies[i+1] + "</option>");
											  	}
											}
										%>
										</SELECT>
									</td>
								</tr>
							</table>
						</div>
						<div style="PADDING-RIGHT: 0px; PADDING-LEFT: 0px; PADDING-BOTTOM: 8px; PADDING-TOP: 3px" >
							<table style="MARGIN: 0px 0px 0px 9px; WIDTH: 710px" cellpadding="0" cellspacing="0">
								<tr>
									<td style="FONT: 11px arial, verdana, sans-serif; WIDTH: 250px"><strong>Address</strong></td>
									<td style="FONT: 11px arial, verdana, sans-serif; WIDTH: 33%"><strong>Shareholders</strong></td>
								</tr>
								<tr>
									<td>
										<DIV id="divAddress" style="MARGIN: 0px 10px 0px 0px;BORDER: 1px solid;overflow:auto; HEIGHT:70px; WIDTH: 240px; FONT: 11px arial, verdana, sans-serif;"></DIV>
									</td>
									<td>
										<DIV id="divShareholders" style="MARGIN: 0px 10px 0px 0px;BORDER: 1px solid;overflow:auto;HEIGHT:70px; WIDTH: 458px; FONT: 11px arial, verdana, sans-serif;" ></DIV>
									</td>
								</tr>
								<tr>
									<td style="FONT: 11px arial, verdana, sans-serif; WIDTH: 33%"><strong>Directors &amp; Company Secretary</strong></td>
									<td style="FONT: 11px arial, verdana, sans-serif; WIDTH: 33%"><strong>Ultimate Parent(UP), Parent(P), Subsidiaries Undertakings(S)</strong></td>
								</tr>
								<tr>
									<td>
										<SELECT name="lstDirectors" style="MARGIN: 0px 10px 0px 0px;HEIGHT:72px; WIDTH: 240px;FONT: 11px arial, verdana, sans-serif;" MULTIPLE onchange="searchCompanyByDirector(this.value,this.form)"></SELECT>
									</td>
									<td>
										<DIV id="divSubsidiary" style="MARGIN: 0px 10px 0px 0px;BORDER: 1px solid;overflow:auto;HEIGHT:70px; WIDTH: 458px;FONT: 11px arial, verdana, sans-serif;" ></DIV>
									</td>
								</tr>
								<tr>
									<td  style="FONT: 11px arial, verdana, sans-serif; WIDTH: 33%" colspan="2"><strong>Business Description</strong></td>
								</tr>
								<tr>
									<td colspan="2"><DIV style="BORDER: 1px solid;overflow:auto;MARGIN: 0px; WIDTH: 708px; HEIGHT:30px; FONT: 11px arial, verdana, sans-serif;" id="divBusinessDescription"></DIV>
									</td>
								</tr>
								<tr>
									<td  style="FONT: 11px arial, verdana, sans-serif; WIDTH: 33%" colspan="2"><strong>Summary Financials</strong>
									</td>
								</tr>
								<tr>
									<td colspan="2">
										<DIV id="divSummaryFinancial" style="BORDER: 1px solid;overflow:auto;MARGIN: 0px; WIDTH: 708px; HEIGHT:220px; FONT: 11px arial, verdana, sans-serif;"></DIV>
									</td>
								</tr>
							</table>
						</div>
					</FORM>
		  </div>
		<!-- tab 1 ends -->
		<!-- tab 2 starts -->
		  <div id="divSourceListTab" style="MARGIN:0; BACKGROUND-COLOR: white;border-style:solid;border-width:1px;border-color:yellow;display:none">
		  	<p>
		  	<div style="FONT: 11px arial, verdana, sans-serif;height:10px;">&nbsp;&nbsp;&nbsp;&nbsp;Source Lists for the <%= session.getAttribute("reportTitle")%> report</div>
			<P>
				<div>
					<TABLE id=TABLE1 cellSpacing=1 cellPadding=1 width="100%" border=0>
						<TR>
							<TD width="50%">
								<p/>
								<form name="frmSourceList">
									&nbsp;&nbsp;
									<SELECT name="selSourceList" style="WIDTH: 271px; HEIGHT: 316px;FONT: 11px arial, verdana, sans-serif;" size=2 onchange="displaySourceDetails(document.frmSourceDetails,this.selectedIndex)">
									</SELECT>
					  			</form>
							</TD>
							<TD width="50%" valign=top>
				  				<form name="frmSourceDetails">
				  					<div id ="divSourceListMessage" style="FONT: 11px arial, verdana, sans-serif;height:10px;">
				  						New Source List
									</div>
									<P>
									<INPUT name="txtURL" size=33 style="WIDTH: 260px; HEIGHT: 20px;FONT: 11px arial, verdana, sans-serif;">
									</P>
									<P>
										<TEXTAREA name="txtNotes" style="WIDTH: 267px; HEIGHT: 55px;FONT: 11px arial, verdana, sans-serif;text-transform:lowercase" rows=5 cols=29></TEXTAREA>
										&nbsp;
									</P>
									<table style="FONT: 11px arial, verdana, sans-serif;">
										<tr>
											<td width="30%">Association Indicator</td>
											<td><input type=checkbox name="chkAssociationIndicator"></td>
										</tr>
										<tr>
											<td width="30%"><br>Quality Score</td>
											<td>
												Low&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;High
												<br>
												<input type=radio name="radQualityScore" value="0" checked>&nbsp;
												<input type=radio name="radQualityScore" value="1">&nbsp;
												<input type=radio name="radQualityScore" value="2">
											</td>
										</tr>
										<tr>
											<td width="30%">Date Last Checked </td>
											<td><input type="text" style=" HEIGHT: 20px;FONT: 11px arial, verdana, sans-serif;" name="txtDateLastChecked" onfocus="this.blur()"></td>
										</tr>
									</table>
									<P>&nbsp;</P>
									<table width="100%">
										<tr>
											<td align="right">
												<P>
													&nbsp;&nbsp;<INPUT style="WIDTH: 75px; HEIGHT: 20px" type=button size=43 value="Update" onclick="updateSourceList(this.form)">&nbsp;
													<INPUT style="WIDTH: 75px; HEIGHT: 20px" type=button size=41 value="New URL" onclick="createNewURL(this.form)">
													&nbsp;&nbsp;<INPUT style="WIDTH: 75px; HEIGHT: 20px" type=button size=43 value="Delete" onclick="deleteSourceList(this.form)">
												</P>
											</td>
										</tr>
										<tr>
											<td>
												<p> &nbsp;<p>
												<input type=button value="Send Source Lists"  style="WIDTH: 126px; HEIGHT: 20px;align:right" onclick="emailSourceList()">
											</td>
										</tr>
									</table>
								</form>
							</TD>
						</TR>
					</TABLE>
				</div>
			</P>
		  </div>
		<!-- tab 2 ends -->
		<!-- tab 3 starts -->
		<div id="divWebsiteDetailsTab" style="MARGIN:0; BACKGROUND-COLOR: white;border-style:solid;border-width:1px;border-color:yellow;display:none">
		  	<p>
		  	<div style="FONT: 11px arial, verdana, sans-serif;height:10px;">&nbsp;&nbsp;&nbsp;&nbsp;Companies in the <%= session.getAttribute("reportTitle")%> report</div>
			<P>
				<div>
					<TABLE id=TABLE1 cellSpacing=1 cellPadding=1 width="100%" border=0>
						<TR>
							<TD width="50%">
								<p/>
								<form name="frmCompanyList">
									&nbsp;&nbsp;
									<SELECT name="selCompanyList" style="WIDTH: 271px; HEIGHT: 316px;FONT: 11px arial, verdana, sans-serif;" size=2 onchange="displayCompanyDetails(document.frmCompanyDetails,this.selectedIndex)">
									</SELECT>
					  			</form>
							</TD>
							<TD width="50%" valign=top>
				  				<form name="frmCompanyDetails">
				  					<input type="hidden" name="hidRegistrationNumber"/>
				  					<table width="100%" style="FONT: 11px arial, verdana, sans-serif;height:10px;">
					  					<tr>
					  						<td>
					  							<table style="width:365">
					  								<tr>
					  									<td>
															<DIV id="divCompanyDetails" style="padding-left: 3px;BORDER: 1px solid;overflow:auto; HEIGHT:85px; WIDTH: 255px; FONT: 11px arial, verdana, sans-serif;"></DIV>
														</td>
														<td>
															<input type="button" name="btnSearchName" value="Search Name" onclick="return jumpToGoogleSearch('companyName')" style="FONT: 11px arial, verdana, sans-serif;width:100">
															<br>&nbsp;
															<input type="button" name="btnSearchPostcode" value="Search Postcode" onclick="return jumpToGoogleSearch('postcode')" style="FONT: 11px arial, verdana, sans-serif;width:100">
					  									</td>
					  								</tr>
					  							</table>
											</td>
										</tr>
					  					<tr >
					  						<td>Website</td>
										</tr>

										<tr>
											<td>
												<INPUT name="txtCompanyWebsite" size=33 style="WIDTH: 260px; HEIGHT: 20px;FONT: 11px arial, verdana, sans-serif;">
												&nbsp;<input type="button" name="btnGoTo" value="Go To" onclick="return jumpToURL(document.frmCompanyDetails.txtCompanyWebsite.value)" style="FONT: 11px arial, verdana, sans-serif;">
											</td>
										</tr>

					  					<tr>
					  						<td>Generic Email Address</td>
										</tr>
										<tr>
											<td>
												<INPUT name="txtCompanyEmail" size=33 style="WIDTH: 260px; HEIGHT: 20px;FONT: 11px arial, verdana, sans-serif;text-transform:lowercase">
												<br>
												<SPAN style="display:none"><input type="checkbox" name="chkMailDB"> Do Not Mailshot</SPAN>
											</td>
										</tr>
					  					<tr>
					  						<td>Personal Email Address</td>
										</tr>
										<tr>
											<td>
												<INPUT name="txtPersonalEmail" size=33 style="WIDTH: 260px; HEIGHT: 20px;FONT: 11px arial, verdana, sans-serif;">
												<br>
												<SPAN style="display:none"><input type="checkbox" name="chkPersonalMailDB"> Do Not Mailshot</SPAN>
											</td>
										</tr>
										<tr>
											<td>Mr/Ms/Dr&nbsp;&nbsp;First Name&nbsp;&nbsp;&nbsp;&nbsp;Initials&nbsp;Surname</td>
										</tr>
										<tr>
											<td>
												<INPUT name="txtPrefix" style="WIDTH: 45px; HEIGHT: 20px;FONT: 11px arial, verdana, sans-serif;" onblur="this.value = capitalizeWords(this.value)">
												<INPUT name="txtFirstName" style="WIDTH: 60px; HEIGHT: 20px;FONT: 11px arial, verdana, sans-serif;" onblur="this.value = capitalizeWords(this.value);fillInitials(this.form)">
												<INPUT name="txtInitials" style="WIDTH: 30px; HEIGHT: 20px;FONT: 11px arial, verdana, sans-serif;">
												<INPUT name="txtSurname" style="WIDTH: 110px; HEIGHT: 20px;FONT: 11px arial, verdana, sans-serif;" onblur="this.value = capitalizeWords(this.value)">
											</td>
										</tr>
					  					<tr>
					  						<td>Position</td>
										</tr>
										<tr>
											<td>
												<INPUT name="txtPosition" style="WIDTH: 160px; HEIGHT: 20px;FONT: 11px arial, verdana, sans-serif;" onblur="fillPosition(this)">
												&nbsp;<INPUT name="btnUpdate" style="FONT: 11px arial, verdana, sans-serif;" type=button size=43 value="Update" onclick="saveCompanyWebsiteDetails(this.form)">
											</td>
										</tr>
										<tr>
											<td>
												<INPUT id="btnCancel" name="btnCancel" style="WIDTH: 75px; HEIGHT: 25px" type=button size=41 value="Cancel" onclick="expandtab('maintab',0)">
											</td>
										</tr>
									</table>
								</form>
							</TD>
						</TR>
					</TABLE>
				</div>
			</P>
		</div>
		<!-- tab 3 ends -->
	  </td>
	</tr>
	<tr>
		<td><jsp:include page="mr_footer.jsp"/></td>
	</tr>
	</table>
	</div>

		<script type="text/javascript">
			//Start Tab Content script for UL with id="maintab" Separate multiple ids each with a comma.
			initializetabcontent("maintab");

			// retrieve the list of companies from the server.
            getCompanyWebsiteDetailsByReportId();

			//load the menu.
			initjsDOMenu(null);
		</script>
	</body>
</html>